package com.jianguozh.difs.framework.security.service;

import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import com.jianguozh.difs.common.constant.ApiErrorCode;
import com.jianguozh.difs.common.exception.DifsException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.List;

/**
 * 用户详情dao
 *
 * @author hanrs
 * @email 4076130@qq.com
 * @since 2022/3/18 11:29
 */
@Slf4j
@Repository
public class DifsUserDetailsDao {

    @Autowired
    private DataSource dataSource;

    /**
     * 账号检索用户
     *
     * @param username
     * @return
     */
    public Entity loadUserByUsername(String username) {
        String sql = "SELECT * FROM sup_user WHERE del_flag = '0' AND username = ? ";
        try {
            List<Entity> entities = Db.use(dataSource).query(sql, username);
            return entities.size() > 0 ? entities.get(0) : null;
        } catch (SQLException e) {
            log.error("Occur error while access db  using hutools db, reason:{}", e.getMessage());
            throw new DifsException(ApiErrorCode.DATABASE_ERROR);
        }
    }


    /**
     * 获取用户授权的应用集合
     *
     * @param username
     * @return
     */
    public List<Entity> selecListUserClient(String username) {
        String sql = "SELECT sc.* FROM sup_client sc \n" +
                "INNER JOIN sup_role_client src ON src.client_id = sc.id \n" +
                "INNER JOIN sup_role sr ON src.role_id = sr.id AND sr.del_flag ='0'\n" +
                "INNER JOIN sup_user_role sur ON sur.role_id = sr.id  \n" +
                "INNER JOIN sup_user su ON su.id = sur.user_id AND su.del_flag ='0'\n" +
                "WHERE sc.del_flag ='0' AND su.username =?";
        try {
            List<Entity> entities = Db.use(dataSource).query(sql, username);
            return entities;
        } catch (SQLException e) {
            log.error("Occur error while access db  using hutools db, reason:{}", e.getMessage());
            throw new DifsException(ApiErrorCode.DATABASE_ERROR);
        }
    }
}
